package com.miyuan.wm.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.toolkit.CollectionUtils;
import com.google.common.collect.Lists;
import com.miyuan.wm.data.UserInfo;
import com.miyuan.wm.enums.ExceptionCodeEnum;
import com.miyuan.wm.mapper.PermissionMapper;
import com.miyuan.wm.mapper.RoleMapper;
import com.miyuan.wm.mapper.UserMapper;
import com.miyuan.wm.pojo.PermissionEntity;
import com.miyuan.wm.pojo.RoleEntity;
import com.miyuan.wm.pojo.UserEntity;
import com.miyuan.wm.response.BaseResponse;
import com.miyuan.wm.service.UserService;
import com.miyuan.wm.utils.ShiroMD5;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.List;

/**
 * @ClassName UserServiceImpl
 * @Description 用户相关业务类
 */
@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private PermissionMapper permissionMapper;

    @Override
    public List<RoleEntity> findRoles(String userName) {
        // 查询用户信息
        UserEntity userEntity = findUserByUserName(userName);
        if (ObjectUtils.isEmpty(userEntity)) {
            return Lists.newArrayList();
        }
        // 查询角色信息
        List<RoleEntity> roleEntities = roleMapper.listRolesByUserIds(Lists.newArrayList(userEntity.getId()));
        if (CollectionUtils.isEmpty(roleEntities)) {
            return Lists.newArrayList();
        }
        return roleEntities;
    }

    @Override
    public List<PermissionEntity> findPermissions(String userName) {
        // 查询角色信息
        List<RoleEntity> roles = findRoles(userName);
        if (CollectionUtils.isEmpty(roles)) {
            return Lists.newArrayList();
        }
        // 查询权限信息
        List<Integer> roleIds = Lists.newArrayListWithCapacity(roles.size());
        for (RoleEntity role : roles) {
            roleIds.add(role.getId());
        }
        List<PermissionEntity> permissionEntities = permissionMapper.listPermissionsByRoleIds(roleIds);
        if (CollectionUtils.isEmpty(permissionEntities)) {
            return Lists.newArrayList();
        }
        return permissionEntities;
    }

    @Override
    public UserEntity findUserByUserName(String userName) {
        Wrapper<UserEntity> wrapper = new EntityWrapper<>();
        wrapper.eq("user_name", userName);
        List<UserEntity> userEntities = userMapper.selectList(wrapper);
        log.info("查询到用户信息：{}", JSON.toJSONString(userEntities));
        if (CollectionUtils.isEmpty(userEntities)) {
            return new UserEntity();
        }
        return userEntities.get(0);
    }

    @Override
    public BaseResponse<Boolean> updatePassword(UserInfo userInfo, String username, String oldPassWord, String newPassWord, String repeatPassWord) {
        // 根据用户id查询用户信息
        UserEntity userEntity = userMapper.selectById(userInfo.getUserID());
        // 校验用户名密码是否正确
        if (!ObjectUtils.nullSafeEquals(userInfo.getUserName(), username)
                || !ObjectUtils.nullSafeEquals(userEntity.getPassWord(), ShiroMD5.shiroMD5(oldPassWord))) {
            return BaseResponse.errorOf(ExceptionCodeEnum.USERNAME_OR_PASSWORD_ERROR);
        }
        // 校验两次密码是否一致
        if (!ObjectUtils.nullSafeEquals(newPassWord, repeatPassWord)) {
            return BaseResponse.errorOf(ExceptionCodeEnum.THE_TWO_PASSWORDS_DO_NOT_MATCH);
        }
        // 更新密码到数据库
        UserEntity entity = new UserEntity();
        entity.setId(userInfo.getUserID());
        entity.setUserName(userInfo.getUserName());
        entity.setPassWord(ShiroMD5.shiroMD5(newPassWord));
        userMapper.updateById(entity);

        // 更新密码修改信息(是否为初次修改密码)
        Session session = SecurityUtils.getSubject().getSession();
        session.setAttribute("firstLogin", false);
        return BaseResponse.successOf(true);
    }

}
